<template>
  <view class="workorder-manage-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">工单管理</text>
      <text class="nav-add" @click="showAddModal">新增工单</text>
    </view>

   

    <!-- 工单列表 -->
    <view class="workorder-list">
      <view 
        class="workorder-item" 
        v-for="item in workorderList" 
        :key="item.id"
      >
        <view class="item-header">
          <text class="item-title">{{ item.repairType }}</text>
          <text class="item-status" :class="getStatusClass(item.status)">
            {{ item.status }}
          </text>
        </view>
        <view class="item-content">
          <view class="item-row">
            <text class="item-label">房产信息：</text>
            <text class="item-value">{{ item.jzxm }} - {{ item.htbh }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">申请人：</text>
            <text class="item-value">{{ item.createByNickname }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">报障电话：</text>
            <text class="item-value">{{ item.createPhone || '未填写' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">处理人：</text>
            <text class="item-value">{{ item.operaUseNickname || '未分配' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">门禁编码：</text>
            <text class="item-value">{{ item.mjbm || '未填写' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">申请时间：</text>
            <text class="item-value">{{ formatDate(item.createTime) }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">报修内容：</text>
            <text class="item-value description">{{ item.repairContent }}</text>
          </view>
          <view class="item-row" v-if="item.responseContent">
            <text class="item-label">处理回复：</text>
            <text class="item-value description">{{ item.responseContent }}</text>
          </view>
        </view>
        <view class="item-footer">
          <view class="item-actions">
            <text class="action-btn view" @click.stop="viewDetail(item)">查看详情</text>
            <!-- <text class="action-btn edit" @click.stop="editWorkorder(item)" v-if="item.status === '已派单'">编辑</text> -->
            <text class="action-btn assign" @click.stop="assignWorkorder(item)" v-if="item.status === '待派单'">派单</text>
            <text class="action-btn inspect" @click.stop="showInspectModal(item)" v-if="item.status === '已完成'">抽查</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="workorderList.length === 0 && !loading">
      <text class="empty-text">暂无工单信息</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 派单弹窗 -->
    <uni-popup ref="assignPopup" type="bottom">
      <view class="assign-popup">
        <view class="popup-header">
          <text class="popup-title">{{ getAssignPopupTitle() }}</text>
          <text class="popup-close" @click="closeAssignPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="form-item">
            <text class="form-label">选择处理人</text>
            <view class="user-selector">
              <uni-easyinput
                v-model="userSearchKeyword"
                placeholder="请输入姓名或手机号搜索"
                :clearable="true"
                @input="onUserSearch"
              />
              <view class="user-dropdown" v-if="showUserDropdown && filteredUserList.length > 0">
                <view 
                  class="user-item" 
                  v-for="item in filteredUserList" 
                  :key="item.userId"
                  @click="selectUser(item)"
                >
                  <text class="user-name">{{ item.nickName || item.userName }}</text>
                  <text class="user-phone">{{ item.phonenumber }}</text>
                  <text class="user-dept">{{ (item.dept && item.dept.deptName) || '' }}</text>
                </view>
              </view>
              <view class="selected-user" v-if="selectedUserInfo">
                <text class="selected-text">已选择：{{ selectedUserInfo.nickName || selectedUserInfo.userName }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="closeAssignPopup">取消</button>
          <button class="btn-confirm" @click="confirmAssign">确认分配</button>
        </view>
      </view>
    </uni-popup>

    <!-- 新增工单弹窗 -->
    <uni-popup ref="addPopup" type="bottom">
      <view class="add-popup">
        <view class="popup-header">
          <text class="popup-title">新增工单</text>
          <text class="popup-close" @click="$refs.addPopup.close()">×</text>
        </view>
        <view class="popup-content">
          <!-- 选择地址 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>选择地址
            </view>
            <view class="address-selector" @click="openAddressPicker">
              <text class="placeholder-text" v-if="!addForm.fullAddress">请选择省市区镇村/门牌</text>
              <text v-else class="address-text">{{ addForm.fullAddress }}</text>
              <text class="arrow-icon">›</text>
            </view>
            <view v-if="addForm.noAddress" class="no-address-tip">
              未找到您的地址？请拨打客服电话：<text class="phone">4006983338</text>
            </view>
          </view>
          
          <!-- 手机号 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>手机号
            </view>
            <input class="form-input" type="number" v-model="addForm.createPhone" placeholder="请输入手机号" maxlength="11" />
          </view>
          
          <!-- 问题描述 -->
          <view class="form-item">
            <view class="form-label">
              <text class="required">*</text>问题描述
            </view>
            <view class="textarea-container">
              <textarea class="form-textarea" v-model="addForm.description" placeholder="请详细描述您遇到的问题..." maxlength="200" />
              <view class="word-count">{{ addForm.description.length }}/200</view>
            </view>
          </view>
          
          <!-- 图片上传 -->
          <view class="form-item">
            <view class="form-label">
              <text>添加图片</text>
              <text class="upload-tip">(最多可上传9张)</text>
            </view>
            <view class="upload-area">
              <view class="image-preview" v-for="(item, index) in addForm.imageList" :key="index">
                <image :src="item.fileName ? (config.baseUrl + item.fileName) : item.tempPath" mode="aspectFill"></image>
                <view class="delete-icon" @click="deleteImage(index)">
                  <text class="iconfont icon-close">×</text>
                </view>
              </view>
              <view class="upload-btn" @click="chooseImage" v-if="addForm.imageList.length < 9">
                <view class="dashed-border">
                  <view class="upload-icon-container">
                    <uni-icons type="camera-filled" size="24" color="#999"></uni-icons>
                    <text class="upload-text">上传图片</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 报修类型选择 -->
          <view class="repair-type-section">
            <view class="section-title">我想要</view>
            <view class="type-options">
              <view 
                class="type-item" 
                v-for="(item, index) in typeOptions" 
                :key="index"
                :class="{ active: addForm.selectedType === item.value }"
                @click="selectType(item.value)"
              >
                <view class="type-icon" :class="{ 'active-icon': addForm.selectedType === item.value }">
                  <uni-icons :type="item.icon" size="28" :color="addForm.selectedType === item.value ? '#07c160' : '#999'"></uni-icons>
                </view>
                <text class="type-name" :class="{ 'active-text': addForm.selectedType === item.value }">{{ item.name }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="$refs.addPopup.close()">取消</button>
          <button class="btn-confirm" @click="submitRepair">确认新增</button>
        </view>
      </view>
    </uni-popup>

    <!-- 微信风格地址选择弹窗 -->
    <uni-popup ref="addressPopup" type="bottom">
      <view class="wx-popup-content">
        <view class="wx-popup-header">
          <view v-if="deptPath.length > 0" class="wx-back-btn" @click="goBackDept"><text class="wx-back-arrow">←</text></view>
          <view class="wx-breadcrumb">
            <text v-for="(item, idx) in deptPath" :key="item.id" class="wx-breadcrumb-item" @click="goToDept(idx)">{{ item.label }}</text>
          </view>
        </view>
        <view class="wx-popup-title">选择地址</view>
        <view class="wx-list-wrap">
          <view v-for="item in filteredDeptList" :key="item.id" class="wx-list-item"
            :class="{ active: isDeptActive(item) }" @click="onDeptSelect(item)">
            <text>{{ highlightKeyword(item.label, searchKeyword) }}</text>
            <text v-if="item.children && item.children.length" class="wx-arrow">›</text>
          </view>
        </view>
        <view v-if="showHouseList || filteredHouseList.length > 0">
          <view class="wx-popup-title-sub wx-blue-bar">房产地址</view>
          <view class="wx-search-input">
            <uni-easyinput v-model="houseSearchKeyword" placeholder="搜索房产地址" @input="onHouseSearchInput" :clearable="true" />
          </view>
          <view class="wx-list-wrap">
            <view v-for="house in filteredHouseList" :key="house.id" class="wx-list-item"
              @click="onHouseSelect(house)">
              <text class="wx-address-text">{{ getFullDeptNameByIds(house) }}/{{ house.address }}（{{ house.door }}）</text>
            </view>
          </view>
          <view v-if="filteredHouseList.length === 0" class="no-address-tip">
            <view class="no-address-content">
              <uni-icons type="info" size="16" color="#ff6b6b"></uni-icons>
              <text class="no-address-text">未找到您的地址？</text>
            </view>
            <view class="contact-info">
              <text class="contact-label">请拨打客服电话：</text>
              <text class="phone-number" @click="callService">4006983338</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 抽查弹窗 -->
    <uni-popup ref="inspectPopup" type="center">
      <view class="inspect-popup">
        <view class="popup-header">
          <text class="popup-title">工单抽查</text>
          <text class="popup-close" @click="closeInspectPopup">×</text>
        </view>
        <view class="popup-content">
          <view class="inspect-info">
            <text class="inspect-text">请确认工单处理质量是否合格？</text>
            <view class="workorder-info">
              <text class="info-item">工单ID：{{ currentInspectWorkorder ? currentInspectWorkorder.id : '' }}</text>
              <text class="info-item">处理人：{{ currentInspectWorkorder ? currentInspectWorkorder.operaUseNickname : '' }}</text>
              <text class="info-item">完成时间：{{ formatDate(currentInspectWorkorder ? currentInspectWorkorder.updateTime : '') }}</text>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-pass" @click="confirmInspectPass">抽查通过</button>
          <button class="btn-fail" @click="confirmInspectFail">抽查不通过</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getRepairList, getAdslList, addRepair, uploadRepairImage, assignRepair, uploadImage } from '@/api/door/repair'
import { getUserList1 } from '@/api/system/user'
import request from '@/utils/request'
import config from '@/config'

export default {
  data() {
    return {
      config,  // 添加到data中
      stats: {
        totalCount: 0,
        pendingCount: 0,
        completedCount: 0
      },
      workorderList: [],
      houseList: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      addForm: {
        adslId: '',
        createPhone: '',
        description: '',
        imageList: [],
        selectedType: '',
        fullAddress: '',
        noAddress: false,
        addressId: '',
        province: '', 
        city: '', 
        district: '', 
        street: '', 
        village: '', 
        door: ''
      },
      // 地址选择相关数据
      deptTree: [],
      deptPath: [],
      currentDeptList: [],
      searchKeyword: '',
      filteredDeptList: [],
      showHouseList: false,
      houseList: [],
      filteredHouseList: [],
      houseSearchKeyword: '',
      // 报修类型选项
      typeOptions: [
        { name: '安装调试', value: '安装调试', icon: 'gear' },
        { name: '故障维修', value: '故障维修', icon: 'refresh' },
        { name: '网络故障', value: '网络故障', icon: 'wifi' },
        { name: '设备更换', value: '设备更换', icon: 'reload' },
        { name: '其他问题', value: '其他问题', icon: 'help' }
      ],
      // 派单相关数据
      currentWorkorder: null,
      userList: [],
      userSearchKeyword: '',
      showUserDropdown: false,
      filteredUserList: [],
      selectedUserInfo: null,
      // 图片样式配置
      imageStyles: {
        width: 120,
        height: 120
      },
      // 抽查相关数据
      currentInspectWorkorder: null
    }
  },
  onLoad() {
    this.loadData()
    this.loadHouseList()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 显示新增工单弹窗
    showAddModal() {
      this.getDeptTree()
      this.$refs.addPopup.open()
    },
    
    // 获取地址树
    async getDeptTree() {
      try {
        const res = await request({ url: '/system/user/deptTreeNoDataScope', method: 'get' });
        if (res.code === 200 && res.data && res.data.length) {
          this.deptTree = res.data;
        } else {
          this.deptTree = [];
        }
      } catch (e) {
        this.deptTree = [];
      }
    },
    
    // 打开地址选择器
    openAddressPicker() {
      this.deptPath = [];
      this.searchKeyword = '';
      this.houseSearchKeyword = '';
      this.showHouseList = false;
      this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
      this.filteredDeptList = this.currentDeptList;
      
      this.$nextTick(() => {
        this.$refs.addressPopup.open();
      });
    },
    
    // 关闭地址选择器
    closeAddressPopup() {
      this.$refs.addressPopup.close();
      this.searchKeyword = '';
      this.houseSearchKeyword = '';
      this.showHouseList = false;
      this.deptPath = [];
      this.currentDeptList = [];
      this.filteredDeptList = [];
      this.houseList = [];
      this.filteredHouseList = [];
    },
    
    // 返回上级部门
    goBackDept() {
      if (this.deptPath.length > 0) {
        this.deptPath.pop();
        if (this.deptPath.length === 0) {
          this.currentDeptList = this.deptTree.length ? this.deptTree[0].children : [];
        } else {
          this.currentDeptList = this.deptPath[this.deptPath.length - 1].children || [];
        }
        this.filteredDeptList = this.currentDeptList;
        this.searchKeyword = '';
      }
    },
    
    // 跳转到指定层级
    goToDept(idx) {
      this.deptPath = this.deptPath.slice(0, idx + 1);
      this.currentDeptList = this.deptPath[idx].children || [];
      this.filteredDeptList = this.currentDeptList;
      this.searchKeyword = '';
    },
    
    // 判断部门是否激活
    isDeptActive(item) {
      return this.deptPath.length && this.deptPath[this.deptPath.length - 1].id === item.id;
    },
    
    // 选择部门
    onDeptSelect(item) {
      if (item.children && item.children.length) {
        this.deptPath.push(item);
        this.currentDeptList = item.children;
        this.filteredDeptList = this.currentDeptList;
        this.searchKeyword = '';
      } else {
        // 叶子节点（如村居），需要替换而不是添加
        if (!this.deptPath.length || this.deptPath[this.deptPath.length - 1].id !== item.id) {
          // 如果当前路径的最后一个节点也是叶子节点（没有children），先移除它
          if (this.deptPath.length && 
              (!this.deptPath[this.deptPath.length - 1].children || 
               this.deptPath[this.deptPath.length - 1].children.length === 0)) {
            this.deptPath.pop();
          }
          this.deptPath.push(item);
        }
        this.fetchHouseList(item.id);
      }
    },
    
    // 获取房产列表
    async fetchHouseList(deptId) {
      try {
        const res = await request({
          url: '/door/adsl/list',
          method: 'get',
          params: { 
            pageNum: 1, 
            pageSize: 100000,
            village: deptId  // 使用城市ID作为参数
          }
        });
        if (res.code === 200 && res.rows) {
          this.houseList = res.rows;
          this.filteredHouseList = this.houseList;
          console.log('获取房产列表成功:', this.houseList.length, '条');
        } else {
          this.houseList = [];
          this.filteredHouseList = [];
          console.log('获取房产列表失败:', res.msg);
        }
      } catch (e) {
        console.error('获取房产列表异常:', e);
        this.houseList = [];
        this.filteredHouseList = [];
      }
      this.showHouseList = true;
    },

    // 房产搜索
    onHouseSearchInput(val) {
      const keyword = val.trim();
      if (!keyword) {
        this.filteredHouseList = this.houseList;
      } else {
        this.filteredHouseList = this.houseList.filter(house => {
          const searchText = `${house.address || ''} ${house.door || ''} ${house.landlordName || ''} ${house.htbh || ''}`.toLowerCase();
          return searchText.includes(keyword.toLowerCase());
        });
      }
    },
    
    // 选择房产
    onHouseSelect(house) {
      const fullAddress = `${house.provinceName}/${house.cityName}/${house.districtName}/${house.streetName}/${house.villageName}/${house.address}`;
      this.addForm = {
        ...this.addForm,
        addressId: house.id,
        fullAddress,
        province: house.province,
        city: house.city,
        district: house.district,
        street: house.street,
        village: house.village,
        door: house.door,
        noAddress: false
      };
      this.closeAddressPopup();
    },
    
    // 获取完整地址名称
    getFullDeptNameByIds({ province, city, district, street, village }) {
      let names = [];
      let node = this.deptTree && this.deptTree[0];
      if (!node) return '';
      
      function findChild(children, id) {
        if (!children || !id) return null;
        for (let c of children) {
          if (c.id === id) return c;
        }
        return null;
      }
      
      let cur = node;
      if (province && cur) { cur = findChild(cur.children, province); if (cur) names.push(cur.label); }
      if (city && cur) { cur = findChild(cur.children, city); if (cur) names.push(cur.label); }
      if (district && cur) { cur = findChild(cur.children, district); if (cur) names.push(cur.label); }
      if (street && cur) { cur = findChild(cur.children, street); if (cur) names.push(cur.label); }
      if (village && cur) { cur = findChild(cur.children, village); if (cur) names.push(cur.label); }
      return names.join('/');
    },
    
    // 高亮关键词
    highlightKeyword(label, keyword) {
      if (!keyword) return label;
      return label.replace(new RegExp(keyword, 'g'), `<span style="color:#07c160">${keyword}</span>`);
    },
    
    // 选择报修类型
    selectType(value) {
      this.addForm.selectedType = value;
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 9 - this.addForm.imageList.length,
        sizeType: ['compressed'],
        sourceType: ['camera', 'album'],
        success: (res) => {
          res.tempFilePaths.forEach(path => {
            this.addForm.imageList.push({
              tempPath: path,
              fileName: ''
            });
          });
        }
      });
    },
    
    // 删除图片
    deleteImage(index) {
      this.addForm.imageList.splice(index, 1);
    },
    
    // 提交报修
    async submitRepair() {
      // 表单验证
      if (!this.addForm.fullAddress) {
        uni.showToast({ title: '请选择地址', icon: 'none' });
        return;
      }
      if (!this.addForm.createPhone) {
        uni.showToast({ title: '请输入手机号', icon: 'none' });
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.addForm.createPhone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }
      if (!this.addForm.description) {
        uni.showToast({ title: '请输入问题描述', icon: 'none' });
        return;
      }
      if (!this.addForm.selectedType) {
        uni.showToast({ title: '请选择报修类型', icon: 'none' });
        return;
      }
      
      uni.showLoading({ title: '提交中...' });
      
      try {
        // 上传图片
        let imageUrls = [];
        for (let i = 0; i < this.addForm.imageList.length; i++) {
          const image = this.addForm.imageList[i];
          if (image.fileName) {
            // 已上传的图片，直接使用fileName
            imageUrls.push(image.fileName);
            continue;
          }
          
          // 新选择的图片，需要上传
          try {
            const uploadUrl = await uploadImage(image.tempPath);
            console.log('图片上传结果:', uploadUrl);
            if (uploadUrl) {
              // 从url中提取文件路径
              const baseUrl = 'http://charging-prod.szhansel.com/gzyunkong-api/';
              const fileName = uploadUrl.replace('http://charging-prod.szhansel.com/', '');
              console.log('提取的文件路径:', fileName);
              if (fileName) {
                imageUrls.push(fileName);
                // 更新图片列表中的fileName
                this.$set(this.addForm.imageList[i], 'fileName', fileName);
              } else {
                console.error('无法提取文件路径');
                uni.showToast({ title: '图片上传失败', icon: 'none' });
                return;
              }
            } else {
              console.error('图片上传失败:', uploadUrl);
              uni.showToast({ title: '图片上传失败', icon: 'none' });
              return;
            }
          } catch (error) {
            console.error('图片上传异常:', error);
            uni.showToast({ title: '图片上传异常', icon: 'none' });
            return;
          }
        }
        
        console.log('上传的图片列表:', imageUrls);
        
        // 构建提交数据
        const submitData = {
          createPhone: this.addForm.createPhone,
          repairContent: this.addForm.description,
          repairType: this.addForm.selectedType,
          repairImgs: imageUrls.length > 0 ? imageUrls.join(',') : '',
          adslId: this.addForm.addressId,
          houseId: this.addForm.addressId
        };
        
        console.log('提交数据:', submitData);
        
        const res = await addRepair(submitData);
        if (res.code === 200) {
          uni.showToast({ title: '提交成功', icon: 'success' });
          this.$refs.addPopup.close();
          this.resetAddForm();
          this.pageNum = 1;
          this.loadData();
        } else {
          uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
        }
      } catch (error) {
        console.error('提交失败:', error);
        uni.showToast({ title: '提交失败，请重试', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 重置表单
    resetAddForm() {
      this.addForm = {
        adslId: '',
        createPhone: '',
        description: '',
        imageList: [],
        selectedType: '',
        fullAddress: '',
        noAddress: false,
        addressId: '',
        province: '', 
        city: '', 
        district: '', 
        street: '', 
        village: '', 
        door: ''
      };
    },
    
    // 拨打客服电话
    callService() {
      uni.showModal({
        title: '拨打客服电话',
        content: '确定拨打客服电话 4006983338 吗？',
        success: (res) => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: '4006983338',
              success: () => {
                console.log('拨打客服电话成功');
              },
              fail: (err) => {
                console.error('拨打客服电话失败:', err);
                uni.showToast({
                  title: '拨打失败，请手动拨打',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },
    
    // 加载工单数据
    async loadData() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        console.log('查询工单参数:', params)
        const response = await getRepairList(params)
        
        if (response.code === 200) {
          if (this.pageNum === 1) {
            // 强制刷新第一页数据
            this.workorderList = response.rows || []
            console.log('刷新第一页数据，共', this.workorderList.length, '条')
          } else {
            this.workorderList = [...this.workorderList, ...(response.rows || [])]
          }
          
          this.hasMore = response.rows && response.rows.length === this.pageSize
          
          // 更新统计数据
          this.updateStats()
          
          console.log('工单数据:', response.total, '条')
        } else {
          this.$modal.msgError(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 加载房产资料列表
    async loadHouseList() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 1000 // 增加数据量以支持搜索
        }
        
        const response = await getAdslList(params)
        
        if (response.code === 200) {
          this.houseList = (response.rows || []).map(item => ({
            value: item.id,
            text: `${item.jzxm} - ${item.htbh}`,
            address: item.address || '',
            jzxm: item.jzxm,
            htbh: item.htbh
          }))
        }
      } catch (error) {
        console.error('加载房产资料失败:', error)
      }
    },
    
    // 更新统计数据
    updateStats() {
      this.stats.totalCount = this.workorderList.length
      this.stats.pendingCount = this.workorderList.filter(item => item.status === '已派单').length
      this.stats.completedCount = this.workorderList.filter(item => item.status === '已完成').length
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      console.log('查看详情:', item)
      // 将当前行数据编码后传递到详情页面
      const workorderData = encodeURIComponent(JSON.stringify(item))
      uni.navigateTo({
        url: `/pages/workorder/detail?id=${item.id}&workorderData=${workorderData}`,
        success: () => {
          console.log('跳转成功')
        },
        fail: (error) => {
          console.error('跳转失败:', error)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 编辑工单
    editWorkorder(item) {
      uni.navigateTo({
        url: `/pages/workorder/edit?id=${item.id}`
      })
    },
    
    // 派单
    assignWorkorder(item) {
      this.currentWorkorder = item
      this.loadUserList()
      this.$refs.assignPopup.open()
    },
    
    // 关闭派单弹窗
    closeAssignPopup() {
      this.$refs.assignPopup.close()
      this.resetAssignForm()
    },
    
    // 加载用户列表
    async loadUserList() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 1000,
          roleId: 102
        }
        
        const response = await getUserList1(params)
        
        if (response.code === 200) {
          this.userList = response.rows || []
          console.log('用户列表:', this.userList)
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        this.$modal.msgError('加载用户列表失败')
      }
    },
    
    // 用户搜索
    onUserSearch(value) {
      this.userSearchKeyword = value
      if (value) {
        this.filteredUserList = this.userList.filter(item => 
          (item.nickName && item.nickName.includes(value)) || 
          (item.userName && item.userName.includes(value)) ||
          (item.phonenumber && item.phonenumber.includes(value))
        ).slice(0, 10) // 限制显示前10条
        this.showUserDropdown = true
      } else {
        this.showUserDropdown = false
        this.filteredUserList = []
      }
    },
    
    // 选择用户
    selectUser(item) {
      this.selectedUserInfo = item
      this.userSearchKeyword = item.nickName || item.userName
      this.showUserDropdown = false
      this.filteredUserList = []
    },
    
    // 获取分配弹窗标题
    getAssignPopupTitle() {
      if (this.currentWorkorder && this.currentWorkorder.status === '已完成') {
        return '转派工单'
      }
      return '分配工单'
    },
    
    // 确认分配
    async confirmAssign() {
      if (!this.selectedUserInfo) {
        uni.showToast({
          title: '请选择处理人',
          icon: 'none'
        })
        return
      }
      
      const isReassign = this.currentWorkorder && this.currentWorkorder.status === '已完成'
      const actionText = isReassign ? '转派' : '分配'
      const contentText = `确定将工单${actionText}给 ${this.selectedUserInfo.nickName || this.selectedUserInfo.userName} 吗？`
      
      uni.showModal({
        title: `确认${actionText}`,
        content: contentText,
        success: async (res) => {
          if (res.confirm) {
            try {
              const data = {
                operaUserId: this.selectedUserInfo.userId,
                repairOrderId: this.currentWorkorder.id
              }
              
              // 如果是转派，添加备注
              if (isReassign) {
                data.log = '抽查不通过，重新转派'
              }
              
              console.log(`${actionText}工单数据:`, data)
              const response = await assignRepair(data)
              
              if (response.code === 200) {
                this.$modal.msgSuccess(`${actionText}成功`)
                this.$refs.assignPopup.close()
                this.resetAssignForm()
                this.loading = false
                this.loadData() // 刷新列表
              } else {
                this.$modal.msgError(response.msg || `${actionText}失败`)
              }
            } catch (error) {
              console.error(`${actionText}工单失败:`, error)
              this.$modal.msgError('网络异常，请稍后重试')
            }
          }
        }
      })
    },
    
    // 重置分配表单
    resetAssignForm() {
      this.currentWorkorder = null
      this.userSearchKeyword = ''
      this.showUserDropdown = false
      this.filteredUserList = []
      this.selectedUserInfo = null
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        '已派单': 'status-pending',
        '处理中': 'status-accepted',
        '已完成': 'status-completed',
        '已拒绝': 'status-rejected'
      }
      return classMap[status] || 'status-pending'
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 显示抽查弹窗
    showInspectModal(item) {
      this.currentInspectWorkorder = item
      this.$refs.inspectPopup.open()
    },
    
    // 关闭抽查弹窗
    closeInspectPopup() {
      this.$refs.inspectPopup.close()
      this.currentInspectWorkorder = null
    },
    
    // 确认抽查通过
    confirmInspectPass() {
      uni.showModal({
        title: '确认抽查',
        content: '确定抽查通过吗？',
        success: (res) => {
          if (res.confirm) {
            this.$modal.msgSuccess('抽查通过')
            this.closeInspectPopup()
            // 这里可以调用抽查通过的API
            // await inspectPass(this.currentInspectWorkorder.id)
          }
        }
      })
    },
    
    // 确认抽查不通过
    confirmInspectFail() {
      uni.showModal({
        title: '确认抽查',
        content: '确定抽查不通过吗？不通过将转派给其他处理人。',
        success: (res) => {
          if (res.confirm) {
            this.closeInspectPopup()
            // 显示转派弹窗
            this.currentWorkorder = this.currentInspectWorkorder
            this.loadUserList()
            this.$refs.assignPopup.open()
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.workorder-manage-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-add {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.stats-section {
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stats-item {
    text-align: center;
    
    .stats-num {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.workorder-list {
  padding: 20rpx;
}

.workorder-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .item-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      flex: 1;
    }
    
    .item-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-accepted {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &.status-completed {
        background-color: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
      }
    }
  }
  
  .item-content {
    .item-row {
      display: flex;
      margin-bottom: 15rpx;
      
      .item-label {
        font-size: 26rpx;
        color: #666;
        width: 140rpx;
      }
      
      .item-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;
        
        &.description {
          color: #666;
          line-height: 1.5;
        }
      }
    }
  }
  
  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
    
    .item-actions {
      display: flex;
      gap: 20rpx;
      
      .action-btn {
        font-size: 24rpx;
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        
        &.view {
          background-color: #f6ffed;
          color: #52c41a;
        }
        
        &.edit {
          background-color: #e6f7ff;
          color: #1890ff;
        }
        
        &.assign {
          background-color: #f0f8ff;
          color: #722ed1;
        }
        
        &.inspect {
          background-color: #fff7e6;
          color: #fa8c16;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

/* 新增工单弹窗样式 */
.add-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  width: 100vw;
  max-height: 90vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.popup-close {
  font-size: 48rpx;
  color: #999;
  cursor: pointer;
}

.popup-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
}

.required {
  color: #ff4757;
  margin-right: 8rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 30rpx;
  color: #333;
}

.textarea-container {
  position: relative;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 20rpx;
  box-sizing: border-box;
  font-size: 30rpx;
  color: #333;
  resize: none;
}

.word-count {
  position: absolute;
  bottom: 10rpx;
  right: 15rpx;
  font-size: 24rpx;
  color: #999;
}

.upload-tip {
  color: #999;
  font-size: 24rpx;
  margin-left: 10rpx;
}

.upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-preview {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.image-preview image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24rpx;
  cursor: pointer;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
}

.dashed-border {
  width: 100%;
  height: 100%;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.repair-type-section {
  margin-top: 40rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.type-options {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  width: 33.33%;
}

.type-item.active .type-name {
  color: #07c160;
}

.type-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.type-icon.active-icon {
  background-color: #e8f7e8;
}

.type-name {
  font-size: 28rpx;
  color: #666;
}

.type-name.active-text {
  color: #07c160;
}

.address-selector {
  width: 100%;
  height: 80rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  cursor: pointer;
}

.placeholder-text {
  color: #999;
  font-size: 30rpx;
}

.address-text {
  color: #333;
  font-size: 30rpx;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.arrow-icon {
  font-size: 36rpx;
  color: #ccc;
  margin-left: 10rpx;
  transform: rotate(90deg);
}

.no-address-tip {
  background: linear-gradient(135deg, #fff5f5 0%, #fff0f0 100%);
  border: 1px solid #ffebeb;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 16rpx 0;
  text-align: center;
}

.no-address-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12rpx;
}

.no-address-text {
  color: #ff6b6b;
  font-size: 28rpx;
  font-weight: 500;
  margin-left: 8rpx;
}

.contact-info {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.contact-label {
  color: #666;
  font-size: 26rpx;
  margin-right: 8rpx;
}

.phone {
  color: #1989fa;
  font-weight: bold;
}

.phone-number {
  color: #1989fa;
  font-size: 28rpx;
  font-weight: bold;
  text-decoration: underline;
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  background-color: rgba(25, 137, 250, 0.1);
  cursor: pointer;
}

.phone-number:active {
  background-color: rgba(25, 137, 250, 0.2);
}

.popup-footer {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
  border-top: 1px solid #f0f0f0;
}

.btn-cancel, .btn-confirm {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  border: none;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-cancel {
  background-color: #f0f0f0;
  color: #666;
}

.btn-confirm {
  background-color: #07c160;
  color: #fff;
}

/* 地址选择弹窗样式 */
.wx-popup-content {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0 0 24rpx 0;
  min-height: 60vh;
  max-height: 80vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.08);
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}

.wx-popup-header {
  display: flex;
  align-items: center;
  padding: 18rpx 24rpx 0 24rpx;
}

.wx-back-btn {
  margin-right: 12rpx;
  color: #07c160;
  font-size: 36rpx;
  cursor: pointer;
}

.wx-back-arrow {
  font-size: 36rpx;
}

.wx-breadcrumb {
  display: flex;
  flex-wrap: wrap;
}

.wx-breadcrumb-item {
  color: #07c160;
  font-size: 28rpx;
  margin-right: 8rpx;
  cursor: pointer;
}

.wx-breadcrumb-item:after {
  content: ' / ';
  color: #ccc;
  margin-left: 8rpx;
}

.wx-breadcrumb-item:last-child:after {
  content: '';
}

.wx-popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  padding: 24rpx 0 16rpx 0;
}

.wx-popup-title-sub {
  font-size: 28rpx;
  font-weight: 500;
  color: #666;
  padding: 24rpx 24rpx 12rpx 24rpx;
}

.wx-blue-bar {
  border-left: 6rpx solid #07c160;
  padding-left: 18rpx !important;
}

.wx-search-input {
  padding: 0 24rpx 16rpx 24rpx;
}

.wx-list-wrap {
  padding: 0 24rpx;
  max-height: 60vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.wx-list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.wx-list-item:hover {
  background-color: #f8f9fa;
}

.wx-list-item.active {
  background-color: #e8f7e8;
  color: #07c160;
}

.wx-arrow {
  color: #ccc;
  font-size: 24rpx;
}

.wx-address-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

/* 派单弹窗样式 */
.assign-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  width: 100vw;
  max-height: 90vh;
  overflow: hidden;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
    
    .popup-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
    
    .popup-close {
      font-size: 48rpx;
      color: #999;
      cursor: pointer;
    }
  }
  
  .popup-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
    background: #fff;
    
    .form-item {
      margin-bottom: 40rpx;
      
      .form-label {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 16rpx;
      }
      
      .user-selector {
        position: relative;
        
        .user-dropdown {
          position: absolute;
          top: 100%;
          left: 0;
          right: 0;
          background: #fff;
          border-radius: 8rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
          z-index: 100;
          max-height: 400rpx;
          overflow-y: auto;
          
          .user-item {
            padding: 20rpx;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            cursor: pointer;
            
            &:last-child {
              border-bottom: none;
            }
            
            &:hover {
              background: #f8f9fa;
            }
            
            .user-name {
              font-size: 28rpx;
              color: #333;
              margin-right: 20rpx;
            }
            
            .user-phone {
              font-size: 26rpx;
              color: #666;
              margin-right: 20rpx;
            }
            
            .user-dept {
              font-size: 26rpx;
              color: #999;
            }
          }
        }
        
        .selected-user {
          margin-top: 16rpx;
          padding: 16rpx;
          background: #f8f9fa;
          border-radius: 8rpx;
          
          .selected-text {
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    }
  }
  
  .popup-footer {
    padding: 30rpx;
    display: flex;
    gap: 20rpx;
    border-top: 1px solid #f0f0f0;
    background: #fff;
    
    .btn-cancel, .btn-confirm {
      flex: 1;
      height: 80rpx;
      border-radius: 8rpx;
      border: none;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .btn-cancel {
      background-color: #f0f0f0;
      color: #666;
    }
    
    .btn-confirm {
      background-color: #07c160;
      color: #fff;
    }
  }
}

/* 抽查弹窗样式 */
.inspect-popup {
  background: #fff;
  border-radius: 20rpx;
  width: 600rpx;
  max-width: 90vw;
  overflow: hidden;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
    
    .popup-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
    
    .popup-close {
      font-size: 48rpx;
      color: #999;
      cursor: pointer;
    }
  }
  
  .popup-content {
    padding: 30rpx;
    background: #fff;
    
    .inspect-info {
      .inspect-text {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 24rpx;
        display: block;
      }
      
      .workorder-info {
        background: #f8f9fa;
        padding: 20rpx;
        border-radius: 8rpx;
        
        .info-item {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 12rpx;
          display: block;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
  
  .popup-footer {
    padding: 30rpx;
    display: flex;
    gap: 20rpx;
    border-top: 1px solid #f0f0f0;
    background: #fff;
    
    .btn-pass, .btn-fail {
      flex: 1;
      height: 80rpx;
      border-radius: 8rpx;
      border: none;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .btn-pass {
      background-color: #07c160;
      color: #fff;
    }
    
    .btn-fail {
      background-color: #ff4d4f;
      color: #fff;
    }
  }
}
</style> 